package coder.user.service.impl;

import coder.common.BaseContext;
import coder.exception.BaseException;
import coder.user.entity.Comment;
import coder.user.mapper.CommentMapper;
import coder.user.service.ICommentService;
import coder.user.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {
    @Autowired
    private IUserService userService;
    @Override
    public void saveComment(Comment comment) {
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getOrderId, comment.getOrderId()).eq(Comment::getUserId, BaseContext.getCurrentId());
        int count = this.count(queryWrapper);
        if(count == 2) {
            throw new BaseException("最多只能评价两次");
        }
        comment.setUserId(BaseContext.getCurrentId());
        comment.setUserName(userService.getById(BaseContext.getCurrentId()).getName());
        this.save(comment);
    }

    @Override
    public List<Comment> queryComment() {
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getUserId, BaseContext.getCurrentId()).eq(Comment::getIsDelete, 0);
        return this.list(queryWrapper);
    }

    @Override
    public void updateComment(Comment comment) {
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getId, comment.getId()).eq(Comment::getUserId, BaseContext.getCurrentId()).eq(Comment::getIsDelete, 0);
        Comment result = this.getOne(queryWrapper);
        if(result == null || result.getIsDelete() == 1) {
            throw new BaseException("数据不存在");
        }
        this.updateById(comment);
    }
}
